<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">业主管理</h1>
        <p class="page-description">
          无关联房屋住户进入待审核列表;住户迁入房屋后进入已迁入列表;审核不通过进入未通过列表;管理员将住户迁出房屋后,住户进入已迁出列表。
        </p>
      </div>
    </div>

    <!-- 状态标签页 -->
    <div class="status-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="已迁入" :name="1" />
        <el-tab-pane label="待审核" :name="0" />
        <el-tab-pane label="未通过" :name="3" />
        <el-tab-pane label="已迁出" :name="2" />
      </el-tabs>
    </div>

    <!-- 操作按钮栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <!-- 已迁入列表：添加、导入、迁出 -->
        <template v-if="activeTab === 1">
          <el-button type="success" @click="handleAdd">
            <IconifyIconOffline icon="ep:plus" />
            添加
          </el-button>
          <el-button type="success" @click="showImportDialog">
            <IconifyIconOffline icon="ep:upload" />
            导入
          </el-button>
          <el-button
            type="warning"
            :disabled="selectedRows.length === 0"
            @click="() => handleMoveOut()"
          >
            <IconifyIconOffline icon="ep:arrow-right" />
            迁出
          </el-button>
        </template>
        
        <!-- 待审核列表：通过、不通过 -->
        <template v-else-if="activeTab === 0">
          <el-button
            type="primary"
            :disabled="selectedRows.length === 0"
            @click="handleBatchApprove"
          >
            <IconifyIconOffline icon="ep:check" />
            通过
          </el-button>
          <el-button
            :disabled="selectedRows.length === 0"
            @click="handleBatchReject"
          >
            <IconifyIconOffline icon="ep:close" />
            不通过
          </el-button>
        </template>
        
        <!-- 未通过列表：删除 -->
        <template v-else-if="activeTab === 3">
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" />
            删除
          </el-button>
        </template>
        
        <!-- 已迁出列表：删除 -->
        <template v-else-if="activeTab === 2">
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" />
            删除
          </el-button>
        </template>
      </div>
      
      <div class="search-filters">
        <el-input
          v-model="searchForm.ownerName"
          placeholder="业主姓名"
          style="width: 140px;"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-input
          v-model="searchForm.phone"
          placeholder="手机号"
          style="width: 140px;"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-select
          v-model="searchForm.cellId"
          placeholder="小区"
          style="width: 140px;"
          clearable
          @change="handleCellChange"
        >
          <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
          />
        </el-select>
        <!-- 已迁出列表不显示建筑类型、建筑到房屋的搜索 -->
        <template v-if="activeTab !== 2">
          <el-select
            v-model="searchForm.buildingTypeId"
            placeholder="建筑类型"
            style="width: 120px;"
            clearable
            :disabled="!searchForm.cellId"
            @change="handleBuildingTypeChange"
          >
            <el-option
              v-for="type in buildingTypeList"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
          <el-select
            v-model="searchForm.buildingId"
            placeholder="建筑"
            style="width: 120px;"
            clearable
            :disabled="!searchForm.buildingTypeId"
            @change="handleBuildingChange"
          >
            <el-option
              v-for="building in buildingList"
              :key="building.id"
              :label="building.name"
              :value="building.id"
            />
          </el-select>
          <el-select
            v-model="searchForm.houseId"
            placeholder="房屋"
            style="width: 120px;"
            clearable
            filterable
            :disabled="!searchForm.buildingId"
            @change="handleHouseSearch"
          >
            <el-option
              v-for="house in filteredHouseList"
              :key="house.roomId"
              :label="`${house.unit}单元${house.floor}层${house.room}号`"
              :value="house.roomId"
            />
          </el-select>
        </template>
        <el-button type="primary" @click="handleSearch">
          <IconifyIconOffline icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="handleReset">
          <IconifyIconOffline icon="ep:refresh" />
          重置
        </el-button>
      </div>
    </div>

    <!-- 业主列表表格 -->
    <div v-loading="loading" class="table-container">
      <el-table
        ref="tableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ownerName" label="姓名" width="120">
          <template #default="{ row }">
            <div class="name-cell">
              <span>{{ row.ownerName }}</span>
              <IconifyIconOffline icon="ep:plus" class="expand-icon" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="cellName" label="小区" width="120" />
        <!-- 已迁出列表不显示详细房屋信息 -->
        <template v-if="activeTab !== 2">
          <el-table-column prop="buildingName" label="楼宇" width="100" />
          <el-table-column prop="unitName" label="单元" width="100" />
          <el-table-column prop="number" label="房号" width="100" />
        </template>
        <el-table-column prop="residentType" label="住户身份" width="120">
          <template #default="{ row }">
            <el-tag :type="getResidentTypeTag(row.residentType)">
              {{ getResidentTypeText(row.residentType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="业主邮箱" width="190" />
        <!-- 已迁出列表显示注册时间和迁出时间 -->
        <template v-if="activeTab === 2">
          <el-table-column prop="createdTime" label="注册时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="moveInTime" label="迁出时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.moveInTime) }}
            </template>
          </el-table-column>
        </template>
        <!-- 其他列表显示时间信息 -->
        <el-table-column v-else prop="moveInTime" :label="getTimeColumnLabel()" width="160">
          <template #default="{ row }">
            {{ formatDateTime(getTimeFieldValue(row)) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <!-- 待审核列表：只有审核按钮 -->
              <template v-if="activeTab === 0">
                <el-button link type="primary" @click="handleReview(row)">
                  审核
                </el-button>
              </template>
              
              <!-- 已迁入列表：详情、编辑、迁出 -->
              <template v-else-if="activeTab === 1">
                <el-button link type="primary" @click="handleDetail(row)">
                  详情
                </el-button>
                <el-button link type="primary" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button link type="warning" @click="handleMoveOut(row)">
                  迁出
                </el-button>
              </template>
              
              <!-- 已迁出列表：详情、迁入 -->
              <template v-else-if="activeTab === 2">
                <el-button link type="primary" @click="handleDetail(row)">
                  详情
                </el-button>
                <el-button link type="success" @click="handleMoveIn(row)">
                  迁入
                </el-button>
              </template>
              
              <!-- 未通过列表：只有删除 -->
              <template v-else-if="activeTab === 3">
                <el-button link type="danger" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加业主对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加业主"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      class="fullscreen-dialog"
    >
      <!-- 功能说明 -->
      <div class="function-description">
        <ol>
          <li>添加单个新业主，如需批量导入请点击"业主管理——导入"；</li>
          <li>如已迁出用户需再次迁入，请在业主管理中选中已迁出用户进行操作。</li>
        </ol>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="owner-form"
      >
        <!-- 业主基本信息 -->
        <div class="form-section">
          <h3 class="section-title">业主基本信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="姓名" prop="ownerName">
                <el-input v-model="formData.ownerName" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="手机号" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="formData.idCard" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="住户身份" prop="residentType">
                <el-select v-model="formData.residentType" placeholder="请选择住户身份" style="width: 100%">
                  <el-option label="业主" :value="1" />
                  <el-option label="子女" :value="2" />
                  <el-option label="亲戚" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>

              <el-form-item label="入住时间" prop="moveInTime">
                <el-date-picker
                  v-model="formData.moveInTime"
                  type="datetime"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 迁入房屋信息 -->
        <div class="form-section">
          <h3 class="section-title">迁入房屋信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="小区名称" prop="cellId">
                <el-select
                  v-model="formData.cellId"
                  placeholder="请选择小区"
                  style="width: 100%"
                  :loading="loadingOptions.cell"
                  @change="handleCellChange"
                >
                  <el-option
                    v-for="community in communityList"
                    :key="community.id"
                    :label="community.name"
                    :value="community.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建筑类型" prop="buildingTypeId">
                <el-select
                  v-model="formData.buildingTypeId"
                  placeholder="请选择建筑类型"
                  style="width: 100%"
                  :loading="loadingOptions.buildingType"
                  :disabled="!formData.cellId"
                  @change="handleBuildingTypeChange"
                >
                  <el-option
                    v-for="buildingType in buildingTypeList"
                    :key="buildingType.id"
                    :label="buildingType.name"
                    :value="buildingType.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建筑" prop="buildingId">
                <el-select
                  v-model="formData.buildingId"
                  placeholder="请选择建筑"
                  style="width: 100%"
                  :loading="loadingOptions.building"
                  :disabled="!formData.buildingTypeId"
                  @change="handleBuildingChange"
                >
                  <el-option
                    v-for="building in buildingList"
                    :key="building.id"
                    :label="building.name"
                    :value="building.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="房间号" prop="houseId">
                <el-select
                  v-model="formData.houseId"
                  placeholder="---级联楼栋-单元-房间号选择---"
                  style="width: 100%"
                  :loading="loadingOptions.house"
                  :disabled="!formData.buildingId"
                  filterable
                  remote
                  :remote-method="searchHouses"
                  clearable
                >
                  <el-option
                    v-for="house in filteredHouseList"
                    :key="house.roomId"
                    :label="`${house.unit}${house.floor}${house.room}室`"
                    :value="house.roomId"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑业主对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑业主"
      width="60%"
      top="10vh"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="editFormRules"
        label-width="100px"
        class="owner-form"
      >
        <!-- 业主基本信息 -->
        <div class="form-section">
          <h3 class="section-title">业主基本信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="姓名" prop="ownerName">
                <el-input v-model="editFormData.ownerName" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="editFormData.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="手机号" prop="phone">
                <el-input v-model="editFormData.phone" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editFormData.email" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="editFormData.idCard" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="住户身份" prop="residentType">
                <el-select v-model="editFormData.residentType" placeholder="请选择住户身份" style="width: 100%">
                  <el-option label="业主" :value="1" />
                  <el-option label="子女" :value="2" />
                  <el-option label="亲戚" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>

              <el-form-item label="入住时间" prop="moveInTime">
                <el-date-picker
                  v-model="editFormData.moveInTime"
                  type="datetime"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="editFormData.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 业主迁入对话框 -->
    <el-dialog
      v-model="moveInDialogVisible"
      title="业主迁入"
      width="60%"
      top="10vh"
      :close-on-click-modal="false"
    >
      <el-form
        ref="moveInFormRef"
        :model="moveInFormData"
        :rules="moveInFormRules"
        label-width="100px"
        class="owner-form"
      >
        <!-- 业主信息 -->
        <div class="form-section">
          <h3 class="section-title">业主信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="业主姓名">
                <el-input :value="currentMoveInOwner?.ownerName" disabled />
              </el-form-item>
              <el-form-item label="手机号">
                <el-input :value="currentMoveInOwner?.phone" disabled />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 迁入房屋信息 -->
        <div class="form-section">
          <h3 class="section-title">迁入房屋信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="小区" prop="cellId">
                <el-select
                  v-model="moveInFormData.cellId"
                  placeholder="请选择小区"
                  style="width: 100%"
                  @change="handleCellChange"
                >
                  <el-option
                    v-for="community in communityList"
                    :key="community.id"
                    :label="community.name"
                    :value="community.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建筑类型" prop="buildingTypeId">
                <el-select
                  v-model="moveInFormData.buildingTypeId"
                  placeholder="请选择建筑类型"
                  style="width: 100%"
                  :disabled="!moveInFormData.cellId"
                  @change="handleBuildingTypeChange"
                >
                  <el-option
                    v-for="type in buildingTypeList"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建筑" prop="buildingId">
                <el-select
                  v-model="moveInFormData.buildingId"
                  placeholder="请选择建筑"
                  style="width: 100%"
                  :disabled="!moveInFormData.buildingTypeId"
                  @change="handleBuildingChange"
                >
                  <el-option
                    v-for="building in buildingList"
                    :key="building.id"
                    :label="building.name"
                    :value="building.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="房屋" prop="houseId">
                <el-select
                  v-model="moveInFormData.houseId"
                  placeholder="请选择房屋"
                  style="width: 100%"
                  :disabled="!moveInFormData.buildingId"
                  filterable
                >
                  <el-option
                    v-for="house in filteredHouseList"
                    :key="house.roomId"
                    :label="`${house.unit}单元${house.floor}层${house.room}号`"
                    :value="house.roomId"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="迁入时间" prop="moveInTime">
                <el-date-picker
                  v-model="moveInFormData.moveInTime"
                  type="datetime"
                  placeholder="请选择迁入时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="moveInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleMoveInSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入业主对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入业主"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-dialog-content">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传.xlsx/.xls文件，且文件大小不超过10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <p>1. 请按照模板格式填写数据</p>
          <p>2. 住户身份请填写"业主/子女/亲戚/其他"</p>
          <p>3. 确保必填字段都已填写完整</p>
          <p>4. 日期格式请使用YYYY-MM-DD HH:mm:ss</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button @click="handleDownloadTemplate">下载模板</el-button>
          <el-button
            type="primary"
            :loading="importLoading"
            @click="handleImport"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="审核业主"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentReviewOwner" class="owner-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-row">
                <span class="label">姓名：</span>
                <span class="value">{{ currentReviewOwner.ownerName }}</span>
              </div>
              <div class="detail-row">
                <span class="label">性别：</span>
                <span class="value">{{ currentReviewOwner.gender === 1 ? '男' : currentReviewOwner.gender === 2 ? '女' : '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">手机号：</span>
                <span class="value">{{ currentReviewOwner.phone }}</span>
              </div>
              <div class="detail-row">
                <span class="label">邮箱：</span>
                <span class="value">{{ currentReviewOwner.email || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">身份证号：</span>
                <span class="value">{{ currentReviewOwner.idCard || '未设置' }}</span>
              </div>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="detail-section">
              <h4>房屋信息</h4>
              <div class="detail-row">
                <span class="label">小区：</span>
                <span class="value">{{ currentReviewOwner.cellName || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">楼宇：</span>
                <span class="value">{{ currentReviewOwner.buildingName || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">单元：</span>
                <span class="value">{{ currentReviewOwner.unitName || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">房号：</span>
                <span class="value">{{ currentReviewOwner.number || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">住户身份：</span>
                <el-tag :type="getResidentTypeTag(currentReviewOwner.residentType)">
                  {{ getResidentTypeText(currentReviewOwner.residentType) }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="detail-section">
              <h4>时间信息</h4>
              <div class="detail-row">
                <span class="label">申请时间：</span>
                <span class="value">{{ formatDateTime(currentReviewOwner.createdTime) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">更新时间：</span>
                <span class="value">{{ formatDateTime(currentReviewOwner.updatedTime) }}</span>
              </div>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="detail-section">
              <h4>其他信息</h4>
              <div class="detail-row">
                <span class="label">备注：</span>
                <span class="value">{{ currentReviewOwner.remark || '无' }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApprove">通过</el-button>
        <el-button @click="handleReject">不通过</el-button>
      </template>
    </el-dialog>

    <!-- 业主详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="业主详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOwner" class="owner-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-row">
                <span class="label">姓名：</span>
                <span class="value">{{ currentOwner.ownerName }}</span>
              </div>
              <div class="detail-row">
                <span class="label">性别：</span>
                <span class="value">{{ currentOwner.gender === 1 ? '男' : currentOwner.gender === 2 ? '女' : '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">手机号：</span>
                <span class="value">{{ currentOwner.phone }}</span>
              </div>
              <div class="detail-row">
                <span class="label">邮箱：</span>
                <span class="value">{{ currentOwner.email || '未设置' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">身份证号：</span>
                <span class="value">{{ currentOwner.idCard || '未设置' }}</span>
              </div>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="detail-section">
              <h4>房屋信息</h4>
              <div class="detail-row">
                <span class="label">小区：</span>
                <span class="value">{{ currentOwner.cellName || '未设置' }}</span>
              </div>
              <!-- 已迁出列表不显示详细房屋信息 -->
              <template v-if="activeTab !== 2">
                <div class="detail-row">
                  <span class="label">楼宇：</span>
                  <span class="value">{{ currentOwner.buildingName || '未设置' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">单元：</span>
                  <span class="value">{{ currentOwner.unitName || '未设置' }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">房号：</span>
                  <span class="value">{{ currentOwner.number || '未设置' }}</span>
                </div>
              </template>
              <div class="detail-row">
                <span class="label">住户身份：</span>
                <el-tag :type="getResidentTypeTag(currentOwner.residentType)">
                  {{ getResidentTypeText(currentOwner.residentType) }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <div class="detail-section">
              <h4>时间信息</h4>
              <!-- 已迁出列表显示注册时间和已迁出时间 -->
              <template v-if="activeTab === 2">
                <div class="detail-row">
                  <span class="label">注册时间：</span>
                  <span class="value">{{ formatDateTime(currentOwner.createdTime) }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">迁出时间：</span>
                  <span class="value">{{ formatDateTime(currentOwner.moveInTime) }}</span>
                </div>
              </template>
              <!-- 其他列表显示迁入时间和更新时间 -->
              <template v-else>
                <div class="detail-row">
                  <span class="label">{{ activeTab === 0 ? '申请时间' : '迁入时间' }}：</span>
                  <span class="value">{{ formatDateTime(getTimeFieldValue(currentOwner)) }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">更新时间：</span>
                  <span class="value">{{ formatDateTime(currentOwner.updatedTime) }}</span>
                </div>
              </template>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="detail-section">
              <h4>其他信息</h4>
              <div class="detail-row">
                <span class="label">备注：</span>
                <span class="value">{{ currentOwner.remark || '无' }}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit(currentOwner)">编辑</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import {
  getOwnerList,
  createOwner,
  updateOwner,
  deleteOwner,
  batchDeleteOwner,
  getOwnerById,
  moveInOwner,
  moveOutOwner,
  batchMoveOutOwner,
  batchApproveOwner,
  batchDisapproveOwner,
  importOwners,
  exportOwnerTemplate,
  type Owner,
  type OwnerQueryParams,
  type CreateOwnerRequest,
} from "@/api/owner";
import { findAllCells } from "@/api/cell";
import {
  getBuildingTypeList,
  getBuildingList,
  getHouseManagement,
  type BuildingType,
  type BuildingItem,
  type HouseItem
} from "@/api/building";

defineOptions({ name: "DataCenterOwner" });

const router = useRouter();

// 响应式数据
const loading = ref(false);
const tableData = ref<Owner[]>([]);
const selectedRows = ref<Owner[]>([]);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const reviewDialogVisible = ref(false);
const moveInDialogVisible = ref(false);
const currentOwner = ref<Owner | null>(null);
const currentReviewOwner = ref<Owner | null>(null);
const currentMoveInOwner = ref<Owner | null>(null);
const activeTab = ref(1); // 默认显示已迁入状态

// 三级联查相关数据
const communityList = ref<any[]>([]);
const buildingTypeList = ref<BuildingType[]>([]);
const buildingList = ref<BuildingItem[]>([]);
const houseList = ref<HouseItem[]>([]);
const filteredHouseList = ref<HouseItem[]>([]);

const loadingOptions = ref({
  cell: false,
  buildingType: false,
  building: false,
  house: false,
});

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const selectedFile = ref<File | null>(null);
const uploadRef = ref();

// 搜索表单
const searchForm = reactive<OwnerQueryParams & {
  buildingTypeId?: number;
  buildingId?: number;
}>({
  page: 0,
  limit: 10,
  ownerName: "",
  phone: "",
  status: 1, // 默认已迁入状态
  cellId: undefined,
  houseId: undefined,
  buildingTypeId: undefined,
  buildingId: undefined,
});

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 添加表单数据
const formData = reactive<Partial<CreateOwnerRequest> & { 
  ownerName?: string; 
  buildingTypeId?: number;
  buildingId?: number;
}>({
  ownerName: "",
  phone: "",
  cellId: undefined,
  buildingTypeId: undefined,
  buildingId: undefined,
  houseId: undefined,
  email: "",
  gender: 1,
  idCard: "",
  moveInTime: "",
  residentType: 1,
  remark: "",
});

// 编辑表单数据
const editFormData = reactive<{
  id?: number;
  ownerName?: string;
  phone?: string;
  cellId?: number;
  email?: string;
  gender?: number;
  idCard?: string;
  moveInTime?: string;
  residentType?: number;
  remark?: string;
}>({
  id: undefined,
  ownerName: "",
  phone: "",
  cellId: undefined,
  email: "",
  gender: 1,
  idCard: "",
  moveInTime: "",
  residentType: 1,
  remark: "",
});

// 迁入表单数据
const moveInFormData = reactive<{
  ownerId?: number;
  cellId?: number;
  buildingTypeId?: number;
  buildingId?: number;
  houseId?: number;
  moveInTime?: string;
}>({
  ownerId: undefined,
  cellId: undefined,
  buildingTypeId: undefined,
  buildingId: undefined,
  houseId: undefined,
  moveInTime: "",
});

// 迁入表单引用
const moveInFormRef = ref();

// 迁入表单验证规则
const moveInFormRules: FormRules = {
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  buildingTypeId: [{ required: true, message: "请选择建筑类型", trigger: "change" }],
  buildingId: [{ required: true, message: "请选择建筑", trigger: "change" }],
  houseId: [{ required: true, message: "请选择房屋", trigger: "change" }],
  moveInTime: [{ required: true, message: "请选择迁入时间", trigger: "change" }],
};

// 添加表单验证规则（包含房屋相关字段）
const formRules: FormRules = {
  ownerName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  buildingTypeId: [{ required: true, message: "请选择建筑类型", trigger: "change" }],
  buildingId: [{ required: true, message: "请选择建筑", trigger: "change" }],
  houseId: [{ required: true, message: "请选择房屋", trigger: "change" }],
  email: [
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号", trigger: "blur" }
  ],
  moveInTime: [{ required: true, message: "请选择入住时间", trigger: "change" }],
  residentType: [{ required: true, message: "请选择住户身份", trigger: "change" }],
};

// 编辑表单验证规则（不包含房屋相关字段）
const editFormRules: FormRules = {
  ownerName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  email: [
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号", trigger: "blur" }
  ],
  moveInTime: [{ required: true, message: "请选择入住时间", trigger: "change" }],
  residentType: [{ required: true, message: "请选择住户身份", trigger: "change" }],
};

// 表单引用
const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

// 计算属性
const currentQueryParams = computed(() => ({
  page: pagination.page - 1,
  limit: pagination.limit,
  status: activeTab.value,
  ownerName: searchForm.ownerName || undefined,
  phone: searchForm.phone || undefined,
  cellId: searchForm.cellId || undefined,
  houseId: searchForm.houseId || undefined,
}));

// 获取住户身份标签类型
const getResidentTypeTag = (type: number): "success" | "primary" | "warning" | "info" | "danger" => {
  const tagMap: Record<number, "success" | "primary" | "warning" | "info" | "danger"> = {
    1: "success", // 业主
    2: "primary", // 子女
    3: "warning", // 亲戚
    4: "info", // 其他
  };
  return tagMap[type] || "info";
};

// 获取住户身份文本
const getResidentTypeText = (type: number) => {
  const textMap = {
    1: "业主",
    2: "子女",
    3: "亲戚",
    4: "其他",
  };
  return textMap[type as keyof typeof textMap] || "其他";
};

// 获取有效期标签类型
const getValidityTag = (type: number): "success" | "warning" => {
  return type === 1 ? "success" : "warning";
};

// 获取有效期文本
const getValidityText = (type: number) => {
  return type === 1 ? "长期" : "临时";
};

// 获取时间列标签
const getTimeColumnLabel = () => {
  switch (activeTab.value) {
    case 0: // 待审核
      return "申请时间";
    case 1: // 已迁入
      return "迁入时间";
    case 2: // 已迁出
      return "迁出时间";
    case 3: // 未通过
      return "审核时间";
    default:
      return "时间";
  }
};

// 获取时间字段值
const getTimeFieldValue = (row: any) => {
  switch (activeTab.value) {
    case 0: // 待审核
      return row.createdTime || row.moveInTime;
    default:
      return row.moveInTime;
  }
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 获取业主列表
const fetchOwnerList = async () => {
  try {
    loading.value = true;
    const response = await getOwnerList(currentQueryParams.value);
    
    if (response.code === 0 && response.data) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(response.message || "获取业主列表失败");
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取业主列表失败:", error);
    ElMessage.error("获取业主列表失败");
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取社区列表
const fetchCommunityList = async () => {
  try {
    loadingOptions.value.cell = true;
    const response = await findAllCells();
    if (response.code === 0 && response.data) {
      communityList.value = response.data;
    }
  } catch (error) {
    console.error("获取社区列表失败:", error);
  } finally {
    loadingOptions.value.cell = false;
  }
};

// 获取建筑类型列表
const fetchBuildingTypeList = async (cellId: number) => {
  try {
    loadingOptions.value.buildingType = true;
    const response = await getBuildingTypeList(cellId);
    if (response.code === 0 && response.data) {
      buildingTypeList.value = response.data;
    }
  } catch (error) {
    console.error("获取建筑类型列表失败:", error);
    ElMessage.error("获取建筑类型列表失败");
  } finally {
    loadingOptions.value.buildingType = false;
  }
};

// 获取建筑列表
const fetchBuildingList = async (buildingTypeId: number) => {
  try {
    loadingOptions.value.building = true;
    const response = await getBuildingList(buildingTypeId);
    if (response.code === 0 && response.data) {
      buildingList.value = response.data;
    }
  } catch (error) {
    console.error("获取建筑列表失败:", error);
    ElMessage.error("获取建筑列表失败");
  } finally {
    loadingOptions.value.building = false;
  }
};

// 获取房屋列表
const fetchHouseList = async (buildingId: number) => {
  try {
    loadingOptions.value.house = true;
    const response = await getHouseManagement(buildingId);
    if (response.code === 0 && response.data) {
      houseList.value = response.data.roomList;
      filteredHouseList.value = response.data.roomList;
    }
  } catch (error) {
    console.error("获取房屋列表失败:", error);
    ElMessage.error("获取房屋列表失败");
  } finally {
    loadingOptions.value.house = false;
  }
};

// 搜索房屋
const searchHouses = (query: string) => {
  if (!query || query.trim() === "") {
    filteredHouseList.value = houseList.value;
    return;
  }

  const searchTerm = query.toLowerCase().trim();
  filteredHouseList.value = houseList.value.filter(house => {
    const houseText = `${house.unit}${house.floor}${house.room}室`.toLowerCase();
    return houseText.includes(searchTerm);
  });
};

// 级联选择处理函数
const handleCellChange = async (cellId: number) => {
  // 清空添加表单的下级选择
  formData.buildingTypeId = undefined;
  formData.buildingId = undefined;
  formData.houseId = undefined;
  
  // 清空搜索表单的下级选择
  searchForm.buildingTypeId = undefined;
  searchForm.buildingId = undefined;
  searchForm.houseId = undefined;
  
  // 清空迁入表单的下级选择
  moveInFormData.buildingTypeId = undefined;
  moveInFormData.buildingId = undefined;
  moveInFormData.houseId = undefined;
  
  // 清空数据列表
  buildingTypeList.value = [];
  buildingList.value = [];
  houseList.value = [];

  if (cellId) {
    await fetchBuildingTypeList(cellId);
  }
};

const handleBuildingTypeChange = async (buildingTypeId: number) => {
  // 清空添加表单的下级选择
  formData.buildingId = undefined;
  formData.houseId = undefined;
  
  // 清空搜索表单的下级选择
  searchForm.buildingId = undefined;
  searchForm.houseId = undefined;
  
  // 清空迁入表单的下级选择
  moveInFormData.buildingId = undefined;
  moveInFormData.houseId = undefined;
  
  // 清空数据列表
  buildingList.value = [];
  houseList.value = [];

  if (buildingTypeId) {
    await fetchBuildingList(buildingTypeId);
  }
};

const handleBuildingChange = async (buildingId: number) => {
  // 清空添加表单的下级选择
  formData.houseId = undefined;
  
  // 清空搜索表单的下级选择
  searchForm.houseId = undefined;
  
  // 清空迁入表单的下级选择
  moveInFormData.houseId = undefined;
  
  // 清空数据列表
  houseList.value = [];
  filteredHouseList.value = [];

  if (buildingId) {
    await fetchHouseList(buildingId);
  }
};

// 标签页切换
const handleTabChange = (tabName: number) => {
  activeTab.value = tabName;
  searchForm.status = tabName;
  pagination.page = 1;
  fetchOwnerList();
};

// 搜索处理
const handleSearch = () => {
  pagination.page = 1;
  fetchOwnerList();
};

// 重置搜索
const handleReset = () => {
  searchForm.ownerName = "";
  searchForm.phone = "";
  searchForm.cellId = undefined;
  searchForm.buildingTypeId = undefined;
  searchForm.buildingId = undefined;
  searchForm.houseId = undefined;
  
  // 清空三级联查的数据列表
  buildingTypeList.value = [];
  buildingList.value = [];
  houseList.value = [];
  filteredHouseList.value = [];
  
  pagination.page = 1;
  fetchOwnerList();
};

// 筛选处理
const handleFilter = () => {
  // TODO: 实现筛选功能
  ElMessage.info("筛选功能开发中");
};

// 房屋搜索处理
const handleHouseSearch = (houseId: number) => {
  // 房屋选择后的处理逻辑
  console.log("选择的房屋ID:", houseId);
};


// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchOwnerList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchOwnerList();
};

// 表格选择改变
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 添加业主
const handleAdd = () => {
  Object.assign(formData, {
    ownerName: "",
    phone: "",
    cellId: undefined,
    buildingTypeId: undefined,
    buildingId: undefined,
    houseId: undefined,
    email: "",
    gender: 1,
    idCard: "",
    moveInTime: "",
    residentType: 1,
    remark: "",
  });
  addDialogVisible.value = true;
};

// 编辑业主
const handleEdit = async (row: Owner) => {
  try {
    // 先获取业主详情
    const response = await getOwnerById(row.id);
    if (response.code === 0 && response.data) {
      const ownerDetail = response.data;
      console.log("详情接口返回的数据:", ownerDetail);
      console.log("详情接口返回的ID:", ownerDetail.id);
      
      Object.assign(editFormData, {
        id: ownerDetail.id || row.id, // 确保ID不为空，如果详情接口没有返回ID则使用列表的ID
        ownerName: ownerDetail.name, // 详情接口返回的是name字段
        phone: ownerDetail.phone,
        cellId: ownerDetail.cellId,
        email: ownerDetail.email || "",
        gender: ownerDetail.gender || 1,
        idCard: ownerDetail.idCard || "",
        moveInTime: ownerDetail.moveInTime,
        residentType: ownerDetail.residentType,
        remark: ownerDetail.remark || "",
      });
    } else {
      // 如果获取详情失败，使用列表数据
      console.log("获取详情失败，使用列表数据，ID:", row.id);
      Object.assign(editFormData, {
        id: row.id,
        ownerName: row.ownerName,
        phone: row.phone,
        cellId: row.cellId,
        email: row.email || "",
        gender: 1,
        idCard: "",
        moveInTime: row.moveInTime,
        residentType: row.residentType,
        remark: row.remark || "",
      });
    }
    
    console.log("编辑表单数据:", editFormData);
    editDialogVisible.value = true;
  } catch (error) {
    console.error("获取业主详情失败:", error);
    ElMessage.error("获取业主详情失败");
  }
};

// 审核业主
const handleReview = async (row: Owner) => {
  try {
    // 获取业主详情
    const response = await getOwnerById(row.id);
    if (response.code === 0 && response.data) {
      const ownerDetail = response.data;
      // 合并详情数据和列表数据，确保房屋信息和更新时间能正确显示
      currentReviewOwner.value = {
        ...ownerDetail,
        // 确保id字段正确设置（优先使用row.id，因为这是列表中的正确ID）
        id: row.id,
        // 映射字段名：详情接口返回的是name，需要映射为ownerName
        ownerName: ownerDetail.name,
        // 保留列表数据中的房屋信息和更新时间
        cellName: row.cellName,
        buildingName: row.buildingName,
        unitName: row.unitName,
        number: row.number,
        houseId: row.houseId,
        updatedTime: row.updatedTime, // 从列表数据中获取更新时间
        createdTime: row.createdTime, // 从列表数据中获取注册时间
      };
      console.log("审核业主 - 设置currentReviewOwner:", currentReviewOwner.value);
    } else {
      // 如果获取详情失败，使用列表数据
      currentReviewOwner.value = row;
    }
    reviewDialogVisible.value = true;
  } catch (error) {
    console.error("获取业主详情失败:", error);
    ElMessage.error("获取业主详情失败");
    // 出错时使用列表数据
    currentReviewOwner.value = row;
    reviewDialogVisible.value = true;
  }
};

// 通过审核
const handleApprove = async () => {
  if (!currentReviewOwner.value) return;
  
  try {
    console.log("审核通过 - 当前业主ID:", currentReviewOwner.value.id);
    const response = await batchApproveOwner([currentReviewOwner.value.id]);
    if (response.code === 0) {
      ElMessage.success("审核通过成功");
      reviewDialogVisible.value = false;
      fetchOwnerList();
    } else {
      ElMessage.error(response.message || "审核失败");
    }
  } catch (error) {
    console.error("审核失败:", error);
    ElMessage.error("审核失败");
  }
};

// 不通过审核
const handleReject = async () => {
  if (!currentReviewOwner.value) return;
  
  try {
    console.log("审核不通过 - 当前业主ID:", currentReviewOwner.value.id);
    const response = await batchDisapproveOwner([currentReviewOwner.value.id]);
    if (response.code === 0) {
      ElMessage.success("审核不通过成功");
      reviewDialogVisible.value = false;
      fetchOwnerList();
    } else {
      ElMessage.error(response.message || "审核失败");
    }
  } catch (error) {
    console.error("审核失败:", error);
    ElMessage.error("审核失败");
  }
};

// 删除业主
const handleDelete = (row: Owner) => {
  ElMessageBox.confirm(
    `确定要删除业主"${row.ownerName}"吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const response = await deleteOwner(row.id);
        if (response.code === 0) {
          ElMessage.success("删除成功");
          fetchOwnerList();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 批量通过审核
const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要审核的业主");
    return;
  }
  
  ElMessageBox.confirm(
    `确定要通过选中的 ${selectedRows.value.length} 个业主的审核吗？`,
    "批量通过审核",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "success",
    }
  )
    .then(async () => {
      try {
        const ownerIds = selectedRows.value.map(row => row.id);
        const response = await batchApproveOwner(ownerIds);
        if (response.code === 0) {
          ElMessage.success("批量通过审核成功");
          fetchOwnerList();
        } else {
          ElMessage.error(response.message || "批量通过审核失败");
        }
      } catch (error) {
        console.error("批量通过审核失败:", error);
        ElMessage.error("批量通过审核失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 批量不通过审核
const handleBatchReject = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要审核的业主");
    return;
  }
  
  ElMessageBox.confirm(
    `确定要不通过选中的 ${selectedRows.value.length} 个业主的审核吗？`,
    "批量不通过审核",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const ownerIds = selectedRows.value.map(row => row.id);
        const response = await batchDisapproveOwner(ownerIds);
        if (response.code === 0) {
          ElMessage.success("批量不通过审核成功");
          fetchOwnerList();
        } else {
          ElMessage.error(response.message || "批量不通过审核失败");
        }
      } catch (error) {
        console.error("批量不通过审核失败:", error);
        ElMessage.error("批量不通过审核失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的业主");
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个业主吗？`,
    "批量删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const ownerIds = selectedRows.value.map(row => row.id);
        const response = await batchDeleteOwner(ownerIds);
        if (response.code === 0) {
          ElMessage.success("批量删除成功");
          fetchOwnerList();
        } else {
          ElMessage.error(response.message || "批量删除失败");
        }
      } catch (error) {
        console.error("批量删除失败:", error);
        ElMessage.error("批量删除失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 查看详情
const handleDetail = async (row: Owner) => {
  try {
    // 获取业主详情
    const response = await getOwnerById(row.id);
    if (response.code === 0 && response.data) {
      const ownerDetail = response.data;
      // 合并详情数据和列表数据，确保房屋信息和更新时间能正确显示
      currentOwner.value = {
        ...ownerDetail,
        // 映射字段名：详情接口返回的是name，需要映射为ownerName
        ownerName: ownerDetail.name,
        // 保留列表数据中的房屋信息和更新时间
        cellName: row.cellName,
        buildingName: row.buildingName,
        unitName: row.unitName,
        number: row.number,
        houseId: row.houseId,
        updatedTime: row.updatedTime, // 从列表数据中获取更新时间
        createdTime: row.createdTime, // 从列表数据中获取注册时间
      };
    } else {
      // 如果获取详情失败，使用列表数据
      currentOwner.value = row;
    }
    detailDialogVisible.value = true;
  } catch (error) {
    console.error("获取业主详情失败:", error);
    ElMessage.error("获取业主详情失败");
    // 出错时使用列表数据
    currentOwner.value = row;
    detailDialogVisible.value = true;
  }
};

// 迁入
const handleMoveIn = (row: Owner) => {
  currentMoveInOwner.value = row;
  // 重置表单数据
  Object.assign(moveInFormData, {
    ownerId: row.id,
    cellId: undefined,
    buildingTypeId: undefined,
    buildingId: undefined,
    houseId: undefined,
    moveInTime: "",
  });
  moveInDialogVisible.value = true;
};


// 迁入表单提交
const handleMoveInSubmit = async () => {
  if (!moveInFormRef.value) return;

  try {
    await moveInFormRef.value.validate();
    
    const moveInData = {
      ownerId: moveInFormData.ownerId,
      houseId: moveInFormData.houseId,
      moveInTime: moveInFormData.moveInTime,
    };
    
    const response = await moveInOwner(moveInData);
    
    if (response.code === 0) {
      ElMessage.success("迁入成功");
      moveInDialogVisible.value = false;
      fetchOwnerList();
    } else {
      ElMessage.error(response.message || "迁入失败");
    }
  } catch (error) {
    console.error("迁入失败:", error);
    ElMessage.error("迁入失败");
  }
};

// 迁出
const handleMoveOut = (row?: Owner) => {
  const targetRows = row ? [row] : selectedRows.value;
  if (targetRows.length === 0) {
    ElMessage.warning("请选择要迁出的业主");
    return;
  }

  const names = targetRows.map(r => r.ownerName).join('、');
  const houseInfo = targetRows.map(r => `${r.cellName}${r.buildingName}${r.unitName}${r.number}号`).join('、');
  ElMessageBox.confirm(
    `确定要将业主"${names}"从房屋"${houseInfo}"迁出吗？`,
    "确认迁出",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      let response;
      if (targetRows.length === 1) {
        // 单个迁出：传入houseId
        response = await moveOutOwner(targetRows[0].houseId);
      } else {
        // 批量迁出：传入houseId数组
        const houseIds = targetRows.map(r => r.houseId);
        response = await batchMoveOutOwner(houseIds);
      }
      
      if (response.code === 0) {
        ElMessage.success("迁出成功");
        fetchOwnerList();
      } else {
        ElMessage.error(response.message || "迁出失败");
      }
    } catch (error) {
      console.error("迁出失败:", error);
      ElMessage.error("迁出失败");
    }
  }).catch(() => {
    // 用户取消
  });
};

// 添加业主提交
const handleAddSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    
    const createData = {
      cellId: formData.cellId,
      name: formData.ownerName,
      phone: formData.phone,
      gender: formData.gender || 0,
      email: formData.email || "",
      remark: formData.remark || "",
      idCard: formData.idCard || "",
      moveInTime: formData.moveInTime || new Date().toISOString(),
      houseId: formData.houseId,
      residentType: formData.residentType || 0,
    };
    
    const response = await createOwner(createData);

    if (response.code === 0) {
      ElMessage.success("创建成功");
      addDialogVisible.value = false;
      fetchOwnerList();
    } else {
      ElMessage.error(response.message || "创建失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("创建失败");
  }
};

// 编辑业主提交
const handleEditSubmit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    
    console.log("提交时的编辑表单数据:", editFormData);
    console.log("提交时的ID:", editFormData.id);
    
    // 检查ID是否存在
    if (!editFormData.id) {
      ElMessage.error("业主ID不能为空");
      return;
    }
    
    const updateData = {
      id: editFormData.id,
      cellId: editFormData.cellId,
      name: editFormData.ownerName,
      phone: editFormData.phone,
      gender: editFormData.gender || 0,
      email: editFormData.email || "",
      remark: editFormData.remark || "",
      idCard: editFormData.idCard || "",
      moveInTime: editFormData.moveInTime || new Date().toISOString(),
      residentType: editFormData.residentType || 0,
    };
    
    console.log("提交的更新数据:", updateData);
    const response = await updateOwner(updateData);

    if (response.code === 0) {
      ElMessage.success("更新成功");
      editDialogVisible.value = false;
      fetchOwnerList();
    } else {
      ElMessage.error(response.message || "更新失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("更新失败");
  }
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  selectedFile.value = null;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 文件选择处理
const handleFileChange = (file: any) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error('只能上传.xlsx/.xls文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  selectedFile.value = file.raw;
  return true;
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await exportOwnerTemplate();
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '业主导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
};

// 处理导入
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning("请先选择要导入的文件");
    return;
  }

  importLoading.value = true;
  try {
    const response = await importOwners(selectedFile.value);
    if (response.code === 0) {
      ElMessage.success("导入成功");
      importDialogVisible.value = false;
      selectedFile.value = null;
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
      await fetchOwnerList();
    } else {
      ElMessage.error(response.message || "导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    importLoading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  fetchOwnerList();
  fetchCommunityList();
});
</script>

<style scoped>
/* 全屏弹窗样式 */
:deep(.fullscreen-dialog) {
  .el-dialog {
    height: 96vh;
    display: flex;
    flex-direction: column;
  }
  
  .el-dialog__body {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }
  
  .el-dialog__header {
    padding: 20px 20px 0;
  }
  
  .el-dialog__footer {
    padding: 0 20px 20px;
  }
}

/* 功能说明样式 */
.function-description {
  background: #f5f7fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.function-description ol {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  line-height: 1.6;
}

.function-description li {
  margin-bottom: 8px;
}

/* 表单样式 */
.owner-form {
  .form-section {
    margin-bottom: 30px;
  }
  
  .section-title {
    margin: 0 0 20px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #409eff;
    padding-bottom: 8px;
  }
  
  .form-content {
    display: flex;
    gap: 30px;
  }
  
  .form-left {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .owner-form .form-content {
    flex-direction: column;
  }
  
  .owner-form .form-left {
    grid-template-columns: 1fr;
  }
}

.main {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.page-description {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.5;
}

.status-tabs {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 4px;
}

.expand-icon {
  font-size: 12px;
  color: #909399;
  cursor: pointer;
}

.expand-icon:hover {
  color: #409eff;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--text) {
  padding: 0;
  margin-right: 8px;
}

:deep(.el-tag) {
  font-size: 12px;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 20px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.import-tips p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 业主详情样式 */
.owner-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 6px;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  width: 80px;
  font-weight: 500;
  color: #606266;
  font-size: 13px;
  flex-shrink: 0;
}

.detail-row .value {
  flex: 1;
  color: #303133;
  font-size: 13px;
  word-break: break-all;
}

/* 审核对话框样式 */
.review-content {
  padding: 10px 0;
}

.review-info {
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.review-info h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 6px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  width: 80px;
  font-weight: 500;
  color: #606266;
  font-size: 13px;
  flex-shrink: 0;
}

.info-row .value {
  flex: 1;
  color: #303133;
  font-size: 13px;
}

.review-actions h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}
</style>
